package com.aviccxzx.smarthome.UserModule;

import android.app.Dialog;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aviccxzx.smarthome.MsgID;
import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.base.GosUserModuleBaseActivity;
import com.aviccxzx.smarthome.entity.AddSceneBean;
import com.aviccxzx.smarthome.entity.CamListBean;
import com.aviccxzx.smarthome.entity.SaveSceneBean;
import com.aviccxzx.smarthome.entity.addMoveLgoic;
import com.aviccxzx.smarthome.netutil.app.App;
import com.aviccxzx.smarthome.netutil.msg.MsgCenter;
import com.aviccxzx.smarthome.service.RetrofitHelper;
import com.aviccxzx.smarthome.service.RetrofitService;
import com.aviccxzx.smarthome.utils.ChangeNameDialogUtil;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.aviccxzx.smarthome.fragment.DeviceListFragment.subList;


/**
 * Created by joey on 2016/10/25.
 */
public class RecommedSceneAct extends GosUserModuleBaseActivity implements View.OnClickListener {

    private Dialog dialog;
    RelativeLayout scene_name_rl;
    TextView scene_name_tv;
    ListView device_list;
    DoubleAdapter adapter;
    List<Object> checkedlist;
    public List<CamListBean.DataBean> cams;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setContentView(com.aviccxzx.smarthome.R.layout.recommend_scene_lay_v19);
        } else {
        }
        initView();
        getCamList();
    }

    public void getCamList() {
        progressDialog.show();
        cams = new ArrayList<>();
        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Call<CamListBean> call = service.getCamlist();
        call.enqueue(new Callback<CamListBean>() {
            @Override
            public void onResponse(Call<CamListBean> call, Response<CamListBean> response) {
                if (response.body() != null && response.body().getData() != null) {
                    int code = response.body().getCode();
                    if (code == 1) {
                        cams.clear();
                        cams.addAll(response.body().getData());
                        initList();
                        progressDialog.dismiss();
                    } else {
                        initList();
                        progressDialog.dismiss();
                    }
                }else {
                    progressDialog.dismiss();
                }
            }

            @Override
            public void onFailure(Call<CamListBean> call, Throwable t) {
                progressDialog.dismiss();
            }
        });
    }

    public void initView() {
        ((TextView) findViewById(com.aviccxzx.smarthome.R.id.title_tv)).setText("推荐场景");
        scene_name_rl = (RelativeLayout) findViewById(R.id.scene_name_rl);
        scene_name_tv = (TextView) findViewById(R.id.scene_name_tv);
        device_list = (ListView) findViewById(R.id.device_list);
        scene_name_rl.setOnClickListener(this);
        findViewById(com.aviccxzx.smarthome.R.id.ll_title_left_view).setOnClickListener(this);
        findViewById(com.aviccxzx.smarthome.R.id.add_scene_btn).setOnClickListener(this);
        checkedlist = new ArrayList<>();
    }

    public void initList() {
        adapter = new DoubleAdapter(subList, cams);
        device_list.setAdapter(adapter);
        device_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (!checkedlist.contains(data.get(position))) {
                    if (checkedlist.size() < 2) {
                        checkedlist.add(data.get(position));
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    checkedlist.remove(data.get(position));
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }

    boolean isDoor, isCam;
    String mac = "";
    String yst = "";

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_title_left_view:
                finish();
                break;
            case R.id.scene_name_rl:
                new ChangeNameDialogUtil(RecommedSceneAct.this, "修改场景名称", new ChangeNameDialogUtil.SureInterfance() {
                    @Override
                    public void sureTodo(String name) {
                        //确定修改 处理方案
                        App.getApp().showToast(name);
                        scene_name_tv.setText(name);
                    }
                }).showSelfDialog();
                break;
            case R.id.add_scene_btn:
                //判断选择的是否是门磁和摄像头
                isCam = false;
                isDoor = false;
                if (checkedlist.size() != 2) {
                    showToast("请先选择设备");
                    return;
                } else {
                    for (int i = 0; i < checkedlist.size(); i++) {
                        if (checkedlist.get(i) instanceof GizWifiDevice) {

                            if (((GizWifiDevice) checkedlist.get(i)).getProductKey().equals(MsgID.PK_DOOR)) {
                                isDoor = true;
                                mac = ((GizWifiDevice) checkedlist.get(i)).getMacAddress();
                            } else {
                                isDoor = false;
                            }
                        } else {
                            isCam = true;
                            yst = ((CamListBean.DataBean) checkedlist.get(i)).getYst();
                        }
                    }
                }
                if (isDoor && isCam) {
                    //门磁和摄像头
                    showToast("对了");
                    //1.添加场景接口
                    makeScene();

                } else {
                    showToast("请选择门磁和摄像机");
                }
                break;
        }
    }

    public void makeScene() {
        progressDialog.show();
        String uid = spf.getString("Uid", "");
        String Mac = spf.getString("gatemac", "");
        String imei = spf.getString("Imei", "");

        String beginTime = "01:00";
        String endTime = "23:59";
        String sceneName = scene_name_tv.getText().toString().trim();

        String choosedWeeks = "1,2,3,4,5,6,7";

        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Gson gson = new Gson();

        /**
         * {
         "begin_time": "string",
         "end_time": "string",
         "frontDto": {
         "imei": "string",
         "mac": "string",
         "uid": "string"
         },
         "scene_id": "string",
         "scene_model": 0,
         "scene_name": "string",
         "scene_switch": 0,
         "weeks": "string"
         }
         */

        AddSceneBean bean = new AddSceneBean();

        bean.setBegin_time(beginTime);
        bean.setEnd_time(endTime);

        AddSceneBean.FrontDtoBean value = new AddSceneBean.FrontDtoBean();
        value.setImei(imei);
        value.setMac(Mac);
        value.setUid(uid);

        bean.setFrontDto(value);
        bean.setScene_id("");
        bean.setScene_model(2);
        bean.setScene_name(sceneName);
        bean.setScene_switch(1);
        bean.setWeeks(choosedWeeks);

        String strEntity = gson.toJson(bean);

        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);
        Call<SaveSceneBean> call = service.saveScene(body);
        call.enqueue(new Callback<SaveSceneBean>() {
            @Override
            public void onResponse(Call<SaveSceneBean> call, Response<SaveSceneBean> response) {
                MsgCenter.fireNull("scene", "");
                String sceneId = response.body().getData().toString();
                //2.添加联动接口
                addMove(sceneId);
            }

            @Override
            public void onFailure(Call<SaveSceneBean> call, Throwable t) {
                progressDialog.dismiss();
                showToast("添加失败");
            }
        });
    }

    List<addMoveLgoic.ExcuteTasksBean> excuteTasks = new ArrayList<addMoveLgoic.ExcuteTasksBean>();
    List<addMoveLgoic.LogicConditionsBean> logicConditions = new ArrayList<>();

    public void addMove(String id) {
        progressDialog.show();
        /**
         * {
         "excuteTasks": [
         {
         "device_type": 0,
         "identification": "string",
         "mac": "string",
         "value": 0
         }
         ],
         "id": "string",
         "logicConditions": [
         {
         "campare": "string",
         "identification": "string",
         "mac": "string",
         "value": 0
         }
         ],
         "name": "string",
         "scene_id": "string"
         }

         门磁 DoorState true是门磁打开报警 false是关闭不报警 对应的值是true-1,false-0；
         水浸 WaterLine 0是不报警，1和2是报警；
         可燃气 AlarmStatus true是报警 false是不报警 对应的值是true-1,false-0；
         声光报警器 AlarmStatus，100是不报警；0、1、2、3都是报警，区分报警设备类型：0是门磁报警，1是水浸报警，2是可燃气报警，3是烟感报警；
         烟雾 SmokeAlarm true是报警 false是不报警 对应的值是true-1,false-0；


         */

        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Gson gson = new Gson();
        addMoveLgoic movelogic = new addMoveLgoic();

        addMoveLgoic.LogicConditionsBean logiccondition = new addMoveLgoic.LogicConditionsBean();

        logiccondition.setCampare("=");
        logiccondition.setIdentification("DoorState");
        logiccondition.setValue(0);
        logiccondition.setDevice_type(5);


        logiccondition.setMac(mac.toLowerCase());

        logicConditions.add(logiccondition);
        movelogic.setLogicConditions(logicConditions);

        addMoveLgoic.ExcuteTasksBean excute = new addMoveLgoic.ExcuteTasksBean();
        excute.setDevice_type(6);
        excute.setIdentification("");
        excute.setValue(0);
        excute.setMac(yst);
        excuteTasks.add(excute);

        movelogic.setExcuteTasks(excuteTasks);
        movelogic.setName("推荐联动");
        movelogic.setId("");
        movelogic.setScene_id(id);

        String strEntity = gson.toJson(movelogic);
        if (logicConditions != null && logicConditions.size() > 0 && excuteTasks != null && excuteTasks.size() > 0) {
            RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);
            Call<ResponseBody> call = service.addSceneLogic(body);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    showToast("添加成功");
                    MsgCenter.fireNull("recomend", "");
                    progressDialog.dismiss();
                    finish();
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    progressDialog.dismiss();
                    showToast("添加失败，请稍后重试");
                }
            });
        } else {
            progressDialog.dismiss();
            showToast("添加失败，请稍后重试");
            return;
        }

    }

    //整合数据
    private List<Object> data;

    public class DoubleAdapter extends BaseAdapter {

        public DoubleAdapter(List<GizWifiDevice> as, List<CamListBean.DataBean> bs) {
            data = new ArrayList<>();
            //把数据装载同一个list里面
            //这里把所有数据都转为object类型是为了装载同一个list里面好进行排序
            data.addAll(as);
            data.addAll(bs);
        }

        /**
         * 获得itemView的type
         *
         * @param position
         * @return
         */
        @Override
        public int getItemViewType(int position) {
            int result = 0;
            if (data.get(position) instanceof GizWifiDevice) {
                result = 0;
            } else if (data.get(position) instanceof CamListBean.DataBean) {
                result = 1;
            }
            return result;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int i) {
            return data.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            //根据position获得View的type
            int type = getItemViewType(position);
            if (convertView == null) {
                //实例化
                holder = new ViewHolder();

                convertView = View.inflate(RecommedSceneAct.this, R.layout.recomscene_listitem_lay, null);
                holder.device_img = (ImageView) convertView.findViewById(R.id.recomd_device_img);
                holder.device_name = (TextView) convertView.findViewById(R.id.recomd_device_name);
                holder.device_check = (ImageView) convertView.findViewById(R.id.recomd_device_check);
                convertView.setTag(holder);

            } else {
                //根据不同的type来获得tag
                holder = (ViewHolder) convertView.getTag();
            }

            Object obj = data.get(position);
            //根据不同的type设置数据
            switch (type) {
                case 0:
                    GizWifiDevice device = (GizWifiDevice) obj;
                    holder.device_name.setText((!TextUtils.isEmpty(device.getAlias()) ? device.getAlias() : device.getProductName()) + "报警");
                    if (device.getProductKey().equals(MsgID.PK_DOOR)) {
                        holder.device_img.setImageResource(R.mipmap.door_icon);
                    } else if (device.getProductKey().equals(MsgID.PK_GAS)) {
                        holder.device_img.setImageResource(R.mipmap.gas_icon);
                    } else if (device.getProductKey().equals(MsgID.PK_WATER)) {
                        holder.device_img.setImageResource(R.mipmap.water_icon);
                    } else if (device.getProductKey().equals(MsgID.PK_ALARM)) {
                        holder.device_img.setImageResource(R.mipmap.alarm_icon);
                    } else if (device.getProductKey().equals(MsgID.PK_SMOKE)) {
                        holder.device_img.setImageResource(R.mipmap.smoke_icon);
                    }
                    break;

                case 1:
                    CamListBean.DataBean cam = (CamListBean.DataBean) obj;
                    holder.device_name.setText(cam.getYst() + "抓拍");
                    holder.device_img.setImageResource(R.mipmap.video_icon);
                    break;
            }
            if (checkedlist.contains(data.get(position))) {
                holder.device_check.setImageResource(R.mipmap.checked_circle);
            } else {
                holder.device_check.setImageResource(R.mipmap.unchecked_circle);
            }
            progressDialog.dismiss();
            return convertView;
        }

        public class ViewHolder {
            ImageView device_img;
            TextView device_name;
            ImageView device_check;
        }
    }
}
